package org.fast.cms.utils;

import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.fast.cms.entity.admin.SysUser;

/** 
* 加Slat后再加密工具类
* @author weigen.ye 
* @date 创建时间：2017年6月24日 上午9:28:47 
*/
public class PasswordUtils {

    private RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();
    private String algorithmName = "md5";
    private int hashIterations = 2;

    public void setRandomNumberGenerator(RandomNumberGenerator randomNumberGenerator) {
        this.randomNumberGenerator = randomNumberGenerator;
    }

    public void setAlgorithmName(String algorithmName) {
        this.algorithmName = algorithmName;
    }

    public void setHashIterations(int hashIterations) {
        this.hashIterations = hashIterations;
    }
    
    public void encryptPassword(SysUser user) {
        user.setSalt(randomNumberGenerator.nextBytes().toHex());
        String credentialsSalt=user.getLoginName()+user.getSalt();
        String encryptPassword = new SimpleHash(
                algorithmName,
                user.getPassword(),
                ByteSource.Util.bytes(credentialsSalt),
                hashIterations).toHex();
        //通过加Salt后再加密的密码
        user.setPassword(encryptPassword);
    } 
    
    public static void main(String[] args){
    	PasswordUtils utils=new PasswordUtils();
    	SysUser user=new SysUser();
    	user.setLoginName("admin");
    	user.setPassword("admin");
    	utils.encryptPassword(user);
    	System.out.println("loginName:"+user.getLoginName());
    	System.out.println("password:"+user.getPassword());
    	System.out.println("salt:"+user.getSalt());
    }
}
